Modify images in Swift using ImageMagick
When you are programming for iOS, and you need to modify images, you can use the UIKit
framework. If you are working on a macOS scripting program, you do not have access to it.
You can use third party libraries, like jpeg and png, or you can use an external program, like ImageMagick.
We will use ImageMagick, first with Process, and then with ShellOut.
Setup your machine with ImageMagick
ImageMagick is a free software used to modify, resize, and convert image in many different formats. You can download it directly from the official website, but the preferred installation method is using Homebrew:
brew install imagemagick
which will install version 7. You can install version 6 if you experience problems. Version 6 is still maintained.
Together with magick
, ImageMagick installs other command line tools. After the installation, in terminal run
which magick
to output the location of the ImageMagick binary, which is probably /usr/local/bin/magick
. You will need it later.
Now we can resize an image with
magick mogrify -resize 50% path/to/image.jpg
Run the command line tool from Swift using Process
To run the command line tools from Swift, we will use Process, a class available in the Foundation framework.
let task = Process()
task.executableURL = URL(fileURLWithPath: "/usr/local/bin/magick")
task.arguments = [
"mogrify",
"-resize",
"50%",
"path/to/image.jpg"
]
try task.run()
task.waitUntilExit()
let status = task.terminationStatus
if status == 0 {
fputs("Resizing succeeded.\n", stdout)
} else {
fputs("Resizing failed.\n", stdout)
}
You can see how this is all implemented in version 0.1.0
of a plugin for Publish, a static site generator for Swift developers.
Run the command line tool from Swift using ShellOut
Instead of making use of Process
directly, we can take advantage of existing packages, like ShellOut, which uses Process
under the hood.
After adding ShellOut as a dependency, you can replicate the script above with
let arguments = [
"mogrify",
"-resize",
"50%",
"path/to/image.jpg"
]
do {
try shellOut(to: "/usr/local/bin/magick \(arguments.joined(separator: " "))")
} catch {
let error = error as! ShellOutError
print(error.message)
print(error.output)
}
This is implemented in version 0.2.0
of the plugin.
Leave a comment